package com.example.auth.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * captcha service
 *
 * @author cui haida
 * @version JDK 8
 * 2025/8/5
 */
@Service
public class CaptchaService {

    /**
     * redis
     * key: CAPTCHA: + key
     * value: captcha code
     */
    private final StringRedisTemplate redisTemplate;
    private final Random random = new Random();

    public CaptchaService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * generate captcha code
     * set the answer to redis
     *
     * @param key uuid
     * @return captcha code
     */
    public String generateCaptcha(String key) {
        int a = random.nextInt(10);
        int b = random.nextInt(10);
        int operator = random.nextInt(3); // 0:+, 1:-, 2:*
        String expression;
        int result;

        switch (operator) {
            case 0:
                expression = a + " + " + b;
                result = a + b;
                break;
            case 1:
                expression = a + " - " + b;
                result = a - b;
                break;
            case 2:
                expression = a + " × " + b;
                result = a * b;
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + operator);
        }
        // 验证码的信息存储在redis
        // key is CAPTCHA: + key
        // value is result
        redisTemplate.opsForValue().set("CAPTCHA:" + key, String.valueOf(result), 5, TimeUnit.MINUTES);
        return expression;
    }
}